<template>
    <div class="address-edit-wrap">
        <CommonHeader teleport=".header" title="修改地址" left-arrow @click-left="$router.back()"></CommonHeader>
        <van-address-edit
            :area-list="areaList"
            show-set-default
            show-delete
            save-button-text="保存"
            delete-button-text="删除"
            :address-info="addressInfo"
            :area-columns-placeholder="['请选择', '请选择', '请选择']"
            @save="onSave"
            @delete="onDelete"
            >
        </van-address-edit>
    </div>
</template>

<script setup lang="ts">
    import { ref } from 'vue';
    import { showFailToast, showSuccessToast, showToast } from 'vant';
    import { areaList } from '@vant/area-data';
    import {updateAddressAPI,deleteAddressAPI} from "@/api/address";

    import { useUserid } from '@/hooks/useUserid';
    import { useRouter,useRoute } from 'vue-router';

    const {userid} = useUserid(); // ref对象

    const router = useRouter();
    const route = useRoute();


   console.log(11111, route.query.address);
   console.log(11111, decodeURIComponent(route.query.address as string));
   console.log(11111, JSON.parse(decodeURIComponent(route.query.address as string)));
   


    const addressAdd = ref<any>();

    // 接收数据  1. 解码字符串得到json字符串   2. 解析json为对象数据
    const addressInfo = ref<any>(JSON.parse(decodeURIComponent(route.query.address as string)));


    const onSave = async (info:any) =>{
        console.log("点击保存",info);

        // 合并剩余参数 将country以外的数据整合到一起,放到data中
        const {country,...data} = info;

        try{
            let result = await updateAddressAPI({
                userid:userid.value,
                ...data,
            })
            console.log("地址修改成功");

            showSuccessToast("修改成功");

            router.push("/address/list");
             
        }catch(err:any){
            showFailToast(err.message);
        }
        

    };

    const onDelete = async (info:any) =>{
        console.log("删除",info);

        let addressid = info.addressid;

        try{
            let result = await deleteAddressAPI({
                addressid
            })
            console.log("地址删除成功");
            showSuccessToast("删除成功");
            router.push("/address/list");
        }catch(err:any){
            showFailToast(err.message);
        }
        
    }
</script>

<style scoped>

</style>